package com.ktjy.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.datatype.jsr310.deser.key.LocalDateKeyDeserializer;
import com.ktjy.pojo.SysRight;
import com.ktjy.pojo.SysRoleRight;
import com.ktjy.pojo.SysUser;
import com.ktjy.pojo.vo.SysUserVo;
import com.ktjy.service.SysRightService;
import com.ktjy.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.List;

/**
 * 登录
 */
@Controller
public class LoginController {
    @Autowired
    SysUserService userService;
    @Autowired
    SysRightService sysRightService;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/")
    public Object login() {
        return "login";
    }

    @RequestMapping("/doLogin")
    public Object doLogin(String usrName, String usrPassword, Model model, HttpSession session, Boolean remember) {
//        SysUserVo sysUserVo = userService.loginToken(usrName);
//        System.out.println("是否选择记住密码："+remember);
//        if (sysUserVo == null) {
//            model.addAttribute("message", "账号不存在！");
//            return "login";
//        } else if (sysUserVo.getUsrPassword().equals(usrPassword)){
//            session.setAttribute("loginUser", sysUserVo);
//            if (remember != null) {
//                stringRedisTemplate.opsForValue().set("loginUser", JSON.toJSONString(sysUserVo));
//            }
//            return "main";
//        }else {
//            model.addAttribute("message", "账号或密码错误！");
//            return "login";
//        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(usrName, usrPassword);
        String errStr = stringRedisTemplate.opsForValue().get(usrName + "errStrCount");
        Integer count = errStr != null ? Integer.parseInt(errStr) : 1;
        if (count > 5) {
            stringRedisTemplate.opsForValue().set(usrName + "errStrCount",errStr,Duration.ofMinutes(1));
            model.addAttribute("message", "密码错误次数过多，请稍后再试！");
            return "login";
        }
        SysUserVo sysUserVo;
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            sysUserVo = (SysUserVo) subject.getPrincipal();
            //获取用户拥有的权限
            List<SysRight> rightList = sysRightService.getListSysRightById(sysUserVo.getUsrRoleId());
            sysUserVo.getRole().setRights(rightList);
        } catch (UnknownAccountException e) {
            model.addAttribute("message", "账号不存在！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("message", "账号被禁用！");
            return "login";
        } catch (AuthenticationException e) {
            stringRedisTemplate.opsForValue().increment(usrName + "errStrCount", 1);
            model.addAttribute("message", "账号或密码错误！");
            return "login";
        }
        if (stringRedisTemplate.opsForValue().get(usrName + "errStrCount")!=null){
            stringRedisTemplate.opsForValue().set(usrName + "errStrCount","0",Duration.ofHours(24));
        }
        session.setAttribute("loginUser", sysUserVo);
        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        return "login";
    }
}
